# --- Setup ---
rm(list = ls())
setwd("/Users/John/Dropbox/")

# --- Load Required Packages ---
library(readr)
library(interflex)
library(tidyverse)
library(ggplot2)
library(cowplot)

# --- Load Data ---

df <- as.data.frame(read_csv("JOP_Replication_Materials/appendix/data/final_dataset_alt_strategic.csv"))

# --- Interflex Model ---
intflex <- df %>%
  dplyr::select(isic, isic2, year, sqrtta, alt_strategic, isic_year, median_share, 
                med_hhi_isic2, med_soe_isic2) %>%
  mutate(Strategic = alt_strategic)

intflex <- as.data.frame(intflex)

# --- Poisson Model
bin.p <- interflex(estimator = "binning", Y = "isic_year", D = "Strategic", X = "median_share", 
                   Z = c("med_hhi_isic2", "med_soe_isic2"),
                   data = intflex, vcov.type = "cluster", cl = "isic", 
                   na.rm = TRUE, main = "Marginal Effect of Strategic Status \n Alternative Strategic Measure (Poisson)", Ylabel = "Tech Absorption", 
                   Xlabel = "Median Processing Share", method = "poisson",
                   cex.main = 1, ncols = 1, theme.bw = TRUE, nbins = 3, bin.labs = F)

# --- Linear Model
bin.l <- interflex(estimator = "binning", Y = "sqrtta", D = "Strategic", X = "median_share", 
                   Z = c("med_hhi_isic2", "med_soe_isic2"),
                   data = intflex, vcov.type = "cluster", cl = "isic", 
                   na.rm = TRUE, main = "Marginal Effect of Strategic Status \n Alternative Strategic Measure (Linear)", Ylabel = "Tech Absorption", 
                   Xlabel = "Median Processing Share", method = "linear",
                   cex.main = 1, ncols = 1, theme.bw = TRUE, nbins = 3, bin.labs = F)

# --- Extract figures from interflex models
fig_bin_p <- bin.p$figure  # Poisson plot
fig_bin_l <- bin.l$figure  # Linear plot

# --- Combine the plots side-by-side ---
combined_figure <- plot_grid(fig_bin_p, fig_bin_l, labels = NULL, nrow = 1, align = "v")

# --- Save figure ---
plot_path <-"JOP_Replication_Materials/appendix/output/B_figure_3.pdf"
ggsave(plot_path, combined_figure, width = 14, height = 6)

message("✅ Saved combined figure to: ", plot_path)
browseURL(plot_path)
